package com.ruantu.clothing.controller.wxController;

import com.ruantu.clothing.entity.User;
import com.ruantu.clothing.service.UserService;
import com.ruantu.clothing.util.MD5;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/wxuser")
public class WXUserController {
    @Autowired
    private UserService userService;

    private static final Logger logger = LoggerFactory.getLogger(WXUserController.class);

    @RequestMapping("/wxLogin")
    public String wxLogin(User user, HttpServletRequest request) {
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(user.getUserName(),
                MD5.d5(MD5.d5(user.getPassWord() + "ruantu")));
        try {
            token.setRememberMe(user.isRem());
            subject.login(token);
            Session session = subject.getSession();
            User u = userService.login(user.getUserName());
            session.setAttribute("info", u);
            return "redirect:/wxpd/wxindex.jsp";
        } catch (Exception e) {
            e.printStackTrace();
            HttpSession session1 = request.getSession();
            session1.setAttribute("errorMsg", "用户名或密码错误！");
            return "redirect:/wxpd/wxlogin.jsp";
        }

    }


    /**
     * 退出
     *
     * @return
     */
    @RequestMapping("/wxExit")
    public String wxExit() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout(); // session 会销毁，在SessionListener监听session销毁，清理权限缓存
        return "redirect:/wxpd/wxlogin.jsp";
    }

}
